package experiment_10_22;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;

class PriceCalculator {
    public static void main(String[] args) {
        String filePath = "D:\\Java code\\Untitled\\Untitled1\\src\\experiment_10_22\\products.txt";

        double averagePrice = calculateAveragePrice(filePath);


        System.out.printf("平均价格: %.2f元/台%n", averagePrice);


        appendAveragePriceToFile(filePath, averagePrice);
    }

    public static double calculateAveragePrice(String filePath) {
        double totalPrice = 0;
        int itemCount = 0;

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;

            reader.readLine();


            while ((line = reader.readLine()) != null) {

                String[] parts = line.split(",");
                if (parts.length == 2) {

                    String priceStr = parts[1].replace("元/台", "").trim();
                    double price = Double.parseDouble(priceStr);
                    totalPrice += price;
                    itemCount++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            System.err.println("价格格式错误: " + e.getMessage());
        }


        return itemCount > 0 ? totalPrice / itemCount : 0;
    }

    public static void appendAveragePriceToFile(String filePath, double averagePrice) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {

            writer.write(String.format("平均价格: %.2f元/台%n", averagePrice));
            System.out.println("平均价格已写入文件。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
